<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="visible"
    width="40%"
    @close="handleClose"
  >
    <el-form ref="form" :model="reportFormData" :rules="rules" label-width="100px">
      <el-form-item label="姓名">
        <el-input v-model="reportFormData.ename" readonly></el-input>
      </el-form-item>

      <el-form-item label="日期">
        <el-date-picker
          v-model="reportFormData.reportdate"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
          readonly
          style="width: 100%;"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="出勤状况">
        <el-radio-group 
        v-model="reportFormData.worktype" 
        :disabled="formType === 'detail' || formType === 'view' || isAbsence">
          <el-radio :label="0">上班</el-radio>
          <el-radio :label="1">调休</el-radio>
          <el-radio :label="2">请假</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="工作量">
        <el-input-number
          v-model="reportFormData.workload"
          :min="0"
          :max="1"
          :disabled="formType === 'detail' || formType === 'view' || isAbsence"
          style="width: 100%;"
        ></el-input-number>
      </el-form-item>

      <el-form-item label="加班时间">
        <el-input-number
          v-model="reportFormData.overtime"
          :min="0"
          :max="12"
          label="小时"
          :disabled="formType === 'detail' || formType === 'view' || isAbsence"
          style="width: 100%;"
        ></el-input-number>
      </el-form-item>

      <el-form-item label="项目选择">
        <el-select v-model="reportFormData.pid" placeholder="请选择项目" style="width: 100%;">
          <el-option
            v-for="item in projectOptions"
            :key="item.pid"
            :label="item.pname"
            :value="item.pid"
            :disabled="formType === 'detail' || formType === 'view'"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="说明图片">
        <el-upload
          class="upload"
          action="#"
          list-type="picture-card"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :http-request="handleUpload"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :disabled="formType === 'detail' || formType === 'view' || formType === 'check'"
        >
          <img v-if="imageUrl!== ''" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <!-- 详细说明文本域 -->
      <el-form-item label="详细说明">
        <el-input
          type="textarea"
          v-model="reportFormData.detail"
          :rows="4"
          :disabled="formType === 'detail' || formType === 'view'"
        ></el-input>
      </el-form-item>

      <!-- 审核结果 -->
      <el-form-item label="审核结果" prop="checkdetail" v-if="formType === 'detail' || formType === 'view' || formType === 'resubmit'">
        <el-input
          type="textarea"
          v-model="reportFormData.checkdetail" 
          :rows="4"
          :disabled="formType === 'view' || formType === 'resubmit'"
        ></el-input>
      </el-form-item>

      <!-- new、supplement、resubmit 模式下的按钮 -->
      <el-form-item v-if="['new', 'supplement', 'resubmit'].includes(formType)">
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <el-button @click="handleClose">取消</el-button>
      </el-form-item>
      
      <!-- 详情模式下的按钮 -->
      <el-form-item v-if="formType === 'detail'">
        <el-button type="primary" @click="handleApprove">通过</el-button>
        <el-button type="primary" @click="handleReject">驳回</el-button>
        <el-button @click="handleClose">关闭</el-button>
      </el-form-item>

      <el-form-item v-if="formType === 'view'">
        <el-button @click="handleClose">关闭</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
export default {
  name: 'ReportForm',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    formType: {
      type: String,
      default: 'new'
    },
    reportData: {
      type: Object,
      default: () => ({})
    },
    lostDate: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      reportFormData: {
        reportid: 0,
        empno: 0,
        ename: '',
        reportdate: this.getTodayDate(),
        worktype: 0, 
        workload: 1, 
        overtime: 0,
        pictureid: '',
        pid: '',
        detail: '',
        checkdetail: '',
        state: 0
      },
      projectOptions: [],
      isAbsence: false,
      rules: {
        checkdetail: [{required: true, message: '请输入审核结果', trigger: 'blur'}]
      },
      deptno: 1,
      fileList: [],
      hasSaved: false, // 标记是否已经保存过
      savedReportId: 0, // 保存后获取的reportid
      imageUrl: '' // 图片URL
    }
  },
  computed: {
    dialogTitle() {
      const titleMap = {
        'new': '每日填报',
        'supplement': '补报',
        'resubmit': '提交报工',
        'detail': '报工审核',
        'view': '查看报工'
      }
      return titleMap[this.formType]
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.loadreportFormData()
      }
    },
    reportData: {
      handler(newVal) {
        if (newVal && Object.keys(newVal).length > 0) {
          this.fillReportFormData(newVal)
        }
      },
      deep: true,
      immediate: true
    },
    // 监听lostDate变化
    lostDate(newVal) {
      if (newVal && this.formType === 'supplement') {
        this.reportFormData.reportdate = newVal
      }
    }
  },
  mounted(){
    this.deptno = localStorage.getItem('deptno')
    this.reportFormData.empno = localStorage.getItem('empno')
    this.reportFormData.ename = localStorage.getItem('ename')
    this.getProjectOptions()
  },
  methods: {
    // 从sessionStorage加载用户信息
    loadUserInfoFromSession() {
      this.reportFormData.ename = localStorage.getItem('ename')
      this.reportFormData.empno = localStorage.getItem('empno')
    },
    
    // 获取今日日期
    getTodayDate() {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0');
      const day = String(today.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 根据表单类型加载数据
    loadreportFormData() {
      this.loadUserInfoFromSession();
      
      // 重置表单数据和状态
      this.reportFormData = {
        reportid: 0,
        empno: this.reportFormData.empno,
        ename: this.reportFormData.ename,
        reportdate: this.getTodayDate(),
        worktype: 0,
        workload: 1,
        overtime: 0,
        pictureid: '',
        pid: 1,
        detail: '',
        checkdetail: '',
        state: 0
      };
      
      // 重置保存状态
      this.hasSaved = false;
      this.savedReportId = 0;
      
      if (this.formType === 'supplement') {
        // supplement模式下使用传入的lostDate
        if (this.lostDate) {
          this.reportFormData.reportdate = this.lostDate;
          this.$http.post('/isAbsence',{
            empno: this.reportFormData.empno,
            date: this.reportFormData.reportdate
          }).then(res => {
            if (res.data === 'fail') {
              this.reportFormData.worktype = 2 // 请假
              this.reportFormData.workload = 0 // 工作时长为0
              this.reportFormData.overtime = 0 // 加班时长为0
              this.isAbsence = true // 标记为缺勤
            }
          }).catch(() => {
            this.$message.error('获取信息失败')
          })
        }
      } else if (this.formType === 'resubmit') {
        // 重新报工模式，使用传入的reportData
        if (this.reportData && Object.keys(this.reportData).length > 0) {
          this.fillReportFormData(this.reportData);
          // 重新报工模式默认已经存在记录，设置为已保存状态
          this.hasSaved = true;
        }
      } else if (this.formType === 'detail' || this.formType === 'view') {
        // 详情模式
        if (this.reportData && Object.keys(this.reportData).length > 0) {
          this.fillReportFormData(this.reportData);
        }
      } else if (this.formType === 'new') {
        this.$http.post('/isAbsence',{
            empno: this.reportFormData.empno,
            date: this.reportFormData.reportdate
          }).then(res => {
            if (res.data === 'fail') {
              this.reportFormData.worktype = 2 // 请假
              this.reportFormData.workload = 0 // 工作时长为0
              this.reportFormData.overtime = 0 // 加班时长为0
              this.isAbsence = true // 标记为缺勤
            }
          }).catch(() => {
            this.$message.error('获取信息失败')
          })
      }
    },
    
    // 填充表单数据
    fillReportFormData(data) {
      // 映射接口返回的数据到表单字段
      this.reportFormData = data

      if (data.pictureid) {
        this.imageUrl = data.pictureid;
      } else {
        this.imageUrl = '';
      }
      
      // 如果数据中有reportid，说明是已存在的记录
      if (data.reportid) {
        this.hasSaved = true;
        this.savedReportId = data.reportid;
      }
    },
    
    // 判断使用哪个URL
    getRequestUrl() {
      // 如果已经保存过或者有reportid，使用编辑接口
      if (this.hasSaved || this.reportFormData.reportid > 0) {
        return '/editReport';
      }
      // 否则使用新增接口
      return '/addReport';
    },
    
    // 保存
    handleSave() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const reportData = {
            ...this.reportFormData,
            state: 0
          }
          const url = this.getRequestUrl
          this.$http.post(url, reportData).then(res => {
            if (res.data === 'success') {
              this.$message.success('保存成功')
              this.hasSaved = true
            } else {
              this.$message.error('保存失败')
            }
          }).catch(error => {
            console.error('保存失败:', error)
            this.$message.error('保存失败')
          })
        } else {
          return false
        }
      })
    },
    
    // 提交报工
    handleSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const reportData = {
            ...this.reportFormData,
            state: 1
          }
          const url = this.getRequestUrl()
          this.$http.post(url, reportData).then(res => {
            if (res.data === 'success') {
              this.$message.success('提交成功')
              this.handleClose()
            } else {
              this.$message.error('提交失败')
            }
          }).catch(() => {
            this.$message.error('提交失败')
          })
        } else {
          return false
        }
      })
    },
    
    // 审核通过
    handleApprove() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const reportData = {
            ...this.reportFormData,
            state: 3
          }
          this.$http.post('/editReport', reportData).then(res => {
            if (res.data === 'success') {
              this.$message.success('审核通过')
              this.handleClose()
            } else {
              this.$message.error('操作失败')
            }
          }).catch(() => {
            this.$message.error('审核失败')
          })
        } else {
          return false
        }
      })
    },
    
    // 审核驳回
    handleReject() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const reportData = {
            ...this.reportFormData,
            state: 0 // 驳回状态
          }
          this.$http.post('/editReport', reportData).then(res => {
            if (res.data === 'success') {
              this.$message.success('已驳回')
              this.handleClose()
            } else {
              this.$message.error('操作失败')
            }
          }).catch(() => {
            this.$message.error('驳回失败')
          })
        } else {
          return false
        }
      })
    },
    
    handleClose() {
      this.imageUrl=''
      this.$refs['form'].resetFields()
      this.$emit('update:visible', false)
      this.$emit('close')
    },

    getProjectOptions(){
        this.$http.get('/getProjectList?deptno=' + this.deptno).then(res=>{
            this.projectOptions = res.data
        }).catch(()=>{
            this.$message.warning('系统异常')
        })
    },

    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG || isPNG && isLt2M
    },

    // 自定义上传方法（核心）
    async handleUpload(config) {
    // config 包含上传的文件信息：config.file 是选中的文件
      const file = config.file
      // 第一步：如果存在旧图片，先删除旧图片
      if (this.reportFormData.pictureid!=='') { // 检查是否有旧图片URL
        try {
          // 调用后端删除图片接口（需后端配合实现）
          await this.$http.post('/deletePicture', { 
            imageUrl: this.reportFormData.pictureid // 传入旧图片的URL
          });
          console.log('旧图片删除成功')
        } catch (err) {
          console.error('删除旧图片失败：', err)
          // 可选：删除旧图失败时，仍可继续上传新图（避免阻塞流程）
          this.$message.warning('旧图片删除失败，但将继续上传新图片')
        }
      }
    
      // 构建formData（文件上传必须用multipart/form-data格式）
      const formData = new FormData()
      formData.append('file', file) // 后端接口用@RequestParam("file")接收
      
      // 调用后端接口
      this.$http.post('/addPicture', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'  // 显式指定内容类型
        }
      }).then(res => {
        // 上传成功：调用el-upload的成功回调，更新组件状态
        if (res.data.code === 200) {
          this.reportFormData.pictureid = res.data.data // 存储后端返回的图片URL
          config.onSuccess(res.data) // 通知组件上传成功
          this.$message.success('图片上传成功')
        } else {
          config.onError(res.data) // 通知组件上传失败
          this.$message.error('图片上传失败：' + res.data.msg)
        }
      }).catch(err => {
        // 网络错误处理
        config.onError(err)
        this.$message.error('上传失败：网络错误')
        console.error('上传错误：', err)
      })
    },

    // 新增：删除图片时清空表单中的图片路径
    handleRemove(file, fileList) {
      if (fileList.length === 0) {
        this.reportFormData.pictureid = '' // 最后一张图片被删除，清空路径
        this.imageUrl = ''
      }
    },

    handleSuccess() {
      this.imageUrl = this.reportFormData.pictureid
    }
  }
}
</script>
<style>
  
</style>